﻿using System;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
using WssEvents;


namespace JQMergeFramework
{
    public class UAVUnit: MonoBehaviour
    {
        
        public Transform[] airfoil;

        public Transform trackNode;

        public Transform models;
        
        //是否点击
        private bool isClickDown = false;
        

        //无人机绑定的建筑
        private CityUnit mCityUnit;
        private TrackUnit mTrack;
        private void OnDisable()
        {
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnTargetEvent,OnTargetEvent);
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnShowEvent,ShowEvent);
            GlobalEvent.Removelistener<EventTypes>(GameEvents.OnCancelUseEvent,DOPlay);
        }

        private void OnEnable()
        {
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnTargetEvent,OnTargetEvent);
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnShowEvent,ShowEvent);
            GlobalEvent.Addlistener<EventTypes>(GameEvents.OnCancelUseEvent,DOPlay);
        }

        private void DOPlay(EventTypes types)
        {
            if (types == EventTypes.UAV)
            {
                this.DOPlay();
                this.transform.DOPlay();
                DOTween.Play(this.GetInstanceID());
            }
        }


        public void ShowEvent(EventTypes types)
        {
            if (types != EventTypes.UAV)
            {
                return;
            }
            
            float speed = 10;
            float y = MainCityControl.I.GetCityNodeHeight(true) + 10;
            
            Vector3 startPos = new Vector3(-50,y,0);
            Vector3 endPos = new Vector3(50,y,0);

            this.transform.position = startPos;
         
            this.models.gameObject.SetActive(true);
            
            Vector3[] path = new Vector3[5];
            path[0] = startPos;
            path[4] = endPos;
            path[2] = (path[0] + path[4]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-30, 5));
            path[1] = (path[0] + path[2]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-20, 10));
            path[3] = (path[2] + path[4]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-30, 5));
            float pathLen = CommonFun.CalculateTotalLength(path);
            float runTime = pathLen / speed;

            Vector3[] path2 = new Vector3[5];
            path2[0] = endPos;
            path2[4] = startPos;
            path2[2] = (path2[0] + path2[4]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-10, 10));
            path2[1] = (path2[0] + path2[2]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-10, 10));
            path2[3] = (path2[2] + path2[4]) / 2f + new Vector3(0, 0, UnityEngine.Random.Range(-10, 10));
            float pathLen2 = CommonFun.CalculateTotalLength(path2);
            float runTime2 = pathLen2 / speed;

            Sequence sq = DOTween.Sequence();
            sq.SetId(this.GetInstanceID());
            sq.Append(this.transform.DOPath(path, runTime, PathType.CatmullRom).SetEase(Ease.Linear));
            sq.Append(this.transform.DOPath(path2, runTime2, PathType.CatmullRom).SetEase(Ease.Linear));
            sq.OnComplete(() =>
            {
                this.models.gameObject.SetActive(false);
            });
            
            //旋转直升机
            for (int i = 0; i < airfoil.Length; i++)
            {
                airfoil[i].DOLocalRotate(new Vector3(0, 360, 0), 0.5f, RotateMode.WorldAxisAdd).SetEase(Ease.Linear)
                    .SetLoops(-1, LoopType.Incremental);
            }

            int lv = MergeManager.Instance.GetPlaceCityMaxLv();
            mCityUnit = TowerControl.I.LoadCityObj(lv);
            mTrack = EffectPool.I.GetPoolObject(PoolName.TrackTemplate).GetComponent<TrackUnit>();
            
            mTrack.SetParent(trackNode);
            mTrack.transform.localPosition = Vector3.zero;
            mTrack.SetIndex(0);
            
            mCityUnit.BindCityTrack(mTrack);
            mCityUnit.transform.localPosition = Vector3.zero + new Vector3(0,TowerControl.I.trackSize.y,0);
        }


        private void OnMouseDown()
        {
            isClickDown = true;
        }

        private void OnMouseUp()
        {
            if (isClickDown && !MergeManager.Instance.isGameOver)
            {
                this.DOPause();
                this.transform.DOPause();
                DOTween.Pause(this.GetInstanceID());
                //UI弹窗
                UIManager.Instance.GetWindow<UIEvent>().Open(EventTypes.UAV);
            }

            isClickDown = false;
        }


        //展示无人机动画
        public void OnTargetEvent(EventTypes types)
        {
            if (types != EventTypes.UAV)
            {
                return;
            }
            
            this.models.gameObject.SetActive(true);
            DOTween.Kill(this.GetInstanceID());
            
            InputManager.I.isNoRayClick = true;
            
            TowerControl.I.ShowPlaceTipsEft(false);
            
            
            Vector3 endTrackPos = TowerControl.I.trackPoint[0].position;
            Vector3 startPos = PositionConvert.ScreenPointToWorldPoint(PositionConvert.UIPointToScreenPointOverlay(
                new Vector3(Screen.width,Screen.height/2)),Math.Abs(GameCameraControl.I.transform.position.z));
            
            //飞行
            Sequence sq = DOTween.Sequence();
            sq.Append(this.transform.DOMove( endTrackPos + new Vector3(0,15,0), 1f));
            sq.AppendCallback(() =>
            {
                //从队列取出，绑定城堡
                CityUnit city = TowerControl.I.DequeueUnitDataBase();
                city.mTrackUnit.transform.DOMove(endTrackPos+ new Vector3(20,0,0),0.3f).OnComplete(() =>
                {
                    city.DestroyTrack();
                    city.RDestroy();
                });
            });
            
            sq.Append(this.transform.DOMoveY(endTrackPos.y, 0.5f).SetEase(Ease.Linear));
            sq.AppendCallback(() =>
            {
                TowerControl.I.ReplaceTowerOneCity(mCityUnit);
                
                mTrack.SetParent(TowerControl.I.towerPlatform);
                
                InputManager.I.isNoRayClick = false;
                TowerControl.I.ShowPlaceTipsEft(true);
            });
            //飞走路线
            sq.Append(this.transform.DOMoveY(endTrackPos.y + 20, 0.3F));
            sq.Append(this.transform.DOMoveX(startPos.x+100, 1F));
            sq.AppendCallback(() =>
            {
                for (int i = 0; i < airfoil.Length; i++)
                {
                    airfoil[i].DOKill();
                }
                this.models.gameObject.SetActive(false);
            });
            sq.Play();
        }
        
        
    }
}